package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.api.publics.MapApi;
import com.jzo2o.api.publics.dto.response.LocationResDTO;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.NumberUtils;
import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageHelperUtils;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {
    @Resource
    private MapApi mapApi;
    @Resource
    private AddressBookMapper addressBookMapper;
    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if(CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }

    @Override
    public void add(AddressBookUpsertReqDTO addressBookUpsertReqDTO) {
        Long userId = UserContext.currentUserId();
        // 如果新增地址设为默认，取消其他默认位置
        if (addressBookUpsertReqDTO.getIsDefault() == 1) {
            cancelDefault(userId);
        }
        AddressBook addressBook = BeanUtils.toBean(addressBookUpsertReqDTO, AddressBook.class);
        addressBook.setUserId(userId);

        // 详细地址
        String complateAddress = addressBookUpsertReqDTO.getProvince()
                + addressBookUpsertReqDTO.getCity()
                + addressBookUpsertReqDTO.getCounty()
                + addressBookUpsertReqDTO.getAddress();
        // 如果没有经纬度，则第三方获取，根据详细地址
        if(ObjectUtils.isEmpty(addressBookUpsertReqDTO.getLocation())){
            // 远程请求高德获取经纬度
            LocationResDTO locationResDTO = mapApi.getLocationByAddress(complateAddress);
            String location = locationResDTO.getLocation();
            addressBookUpsertReqDTO.setAddress(location);
        }
        if(StringUtils.isNotEmpty(addressBookUpsertReqDTO.getLocation())){
            // 经度
            addressBook.setLon(NumberUtils.parseDouble(addressBookUpsertReqDTO.getLocation().split(",")[0]));
            // 纬度
            addressBook.setLat(NumberUtils.parseDouble(addressBookUpsertReqDTO.getLocation().split(",")[1]));
        }
        addressBookMapper.insert(addressBook);
    }

    @Override
    public PageResult<AddressBookResDTO> pageQuery(AddressBookPageQueryReqDTO addressBookPageQueryReqDTO) {
        // 解析分页查询请求
        // 分页请求对象addressBookPageQueryReqDTO， 分页对象page，类型为Page<AddressBook>
        Page<AddressBook> page = PageUtils.parsePageQuery(addressBookPageQueryReqDTO, AddressBook.class);
        // 构建查询条件
        LambdaQueryWrapper<AddressBook> queryWrapper = Wrappers.<AddressBook>lambdaQuery()
                .eq(AddressBook::getUserId, UserContext.currentUserId());
        // 执行查询
        Page<AddressBook> serveTypePage = addressBookMapper.selectPage(page, queryWrapper);
        return PageUtils.toPage(serveTypePage,AddressBookResDTO.class);
//        PageResult<AddressBookResDTO> addressBookResDTOPageResult = PageHelperUtils.selectPage(addressBookPageQueryReqDTO, () ->
//                baseMapper.queryAddressBookByUserId(UserContext.currentUserId()));
//        return addressBookResDTOPageResult;
    }

    @Override
    public void update(Long id, AddressBookUpsertReqDTO addressBookUpsertReqDTO) {
        if(1==addressBookUpsertReqDTO.getIsDefault()){
            cancelDefault(UserContext.currentUserId());
        }
        AddressBook addressBook = BeanUtils.toBean(addressBookUpsertReqDTO, AddressBook.class);
        addressBook.setId(id);

        String complateAddress = addressBookUpsertReqDTO.getProvince()
                + addressBookUpsertReqDTO.getCity()
                + addressBookUpsertReqDTO.getCounty()
                + addressBookUpsertReqDTO.getAddress();
        LocationResDTO locationResDTO = mapApi.getLocationByAddress(complateAddress);
        String location = locationResDTO.getLocation();
        if(StringUtils.isNotEmpty(location)){
            addressBook.setLon(NumberUtils.parseDouble(location.split(",")[0]));
            addressBook.setLat(NumberUtils.parseDouble(location.split(",")[1]));
        }
        addressBookMapper.updateById(addressBook);
    }

    @Override
    public void updateDefaultStatus(Long userId, Long id, Integer flag) {
        if(1==flag){
            cancelDefault(userId);
        }
        AddressBook addressBook = new AddressBook();
        addressBook.setId(id);
        addressBook.setIsDefault(flag);
        addressBookMapper.updateById(addressBook);
    }

    @Override
    public AddressBookResDTO defaultAddress() {
        LambdaQueryWrapper<AddressBook>queryWrapper = Wrappers.<AddressBook>lambdaQuery()
                .eq(AddressBook::getUserId, UserContext.currentUserId())
                .eq(AddressBook::getIsDefault, 1);
        AddressBook addressBook = addressBookMapper.selectOne(queryWrapper);
        return BeanUtils.toBean(addressBook, AddressBookResDTO.class);
    }

    private void cancelDefault(Long userId) {
        lambdaUpdate()
                .eq(AddressBook::getUserId, userId)
                .set(AddressBook::getIsDefault, 0)
                .update();
    }
}
